// pages/other/select_address/select_address.js
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.min');
let qqmapsdk;
let requirePosition;
Page({

  data: {
    longitude: "",
    latitude: "",
    currentSelect: "",
    viewDatas: [],
    searchCity: '上海',
    address: [],
    selectId: "",
    loadingLocation: false,
    searchVal: ""
  },

  onLoad: function (options) {
    requirePosition = getApp().require("/utils/util.js")
    qqmapsdk = new QQMapWX({
      key: getApp().$QQMapKey // 必填
    });

    this.setData({
      currentSelect: getApp().globalData.addressTitle
    });
  },

  onShow: function () {
    this.getPosition();
  },

  inputConfirm: function (e) {
    this.search(e.detail.value);
  },

  search: function name(keyword) {
    let that = this;
    qqmapsdk.search({
      keyword: keyword || '餐饮', //搜索关键词
      location: that.data.latitude + ',' + that.data.longitude,
      page_size: 12,
      success: function (res) { //搜索成功后的回调
        let mks = []
        for (let i = 0; i < res.data.length; i++) {
          if (i == 0) {
            that.setData({
              selectId: res.data[i].id
            })
          }
          mks.push({ // 获取返回结果，放到mks数组中
            title: res.data[i].title,
            id: res.data[i].id,
            latitude: res.data[i].location.lat,
            longitude: res.data[i].location.lng,
            // iconPath: "/resources/my_marker.png", //图标路径
            width: 20,
            height: 20
          })
        }
        that.viewDatas = mks

        that.setData({
          address: res.data
        });
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },

  chooseCity: function () {
    wx.showToast({
      title: '其他城市工作，敬请期待哦~',
      icon: 'none'
    })
  },

  rePosition: function () {
    this.getPosition();
  },

  getPosition: function () {
    let that = this;
    requirePosition.getLocation().then(res => {
      that.setData({
        longitude: res.longitude,
        latitude: res.latitude
      });
      that.search("");
    }).catch(res => {
      console.log("获取定位失败");
    });
  },

  deleteSearchContent: function (e) {
    this.setData({
      searchVal: ""
    });

    this.search("");
  },

  addressClick: function (e) {
    let globalData = getApp().globalData;
    globalData.longitude = e.currentTarget.dataset.longitude;
    globalData.latitude = e.currentTarget.dataset.latitude;
    globalData.address = e.currentTarget.dataset.address;
    globalData.addressTitle = e.currentTarget.dataset.title;

    let data = [globalData.longitude, globalData.latitude, globalData.address, globalData.addressTitle];

    wx.setStorage({
      data: data,
      key: "location",
    })

    const channel = this.getOpenerEventChannel();
    channel.emit("selectAddress")
    wx.navigateBack({
      delta: 1,
    })
  }
})